package com.dabai.iot.core.controller;

import com.dabai.common.core.domain.R;
import com.dabai.common.satoken.utils.LoginHelper;
import com.dabai.common.web.core.BaseController;
import com.dabai.iot.core.service.IHomeService;
import com.dabai.iot.core.vo.HomeCountVO;
import com.dabai.iot.core.vo.HomeLineVO;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;

/**
 * 首页接口 控制器
 *
 * @author kev1n
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/home")
public class HomeController extends BaseController {

    private final IHomeService homeService;

    @GetMapping("/countStatistics")
    @Operation(summary = "数量统计", description = "数量统计")
    public R<HomeCountVO> countStatistics() {
        String tenantId = LoginHelper.getTenantId();
        HomeCountVO homeCount = homeService.countStatistics(tenantId);
        return R.ok(homeCount);
    }

    @GetMapping("/createDeviceStatistics")
    @Operation(summary = "注册设备数统计", description = "折线统计")
    public R<List<HomeLineVO>> createDeviceStatistics(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                                                      @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        validateDate(startDate, endDate);

        String tenantId = LoginHelper.getTenantId();
        List<HomeLineVO> homeDTO = homeService.createDeviceStatistics(tenantId, startDate, endDate);
        return R.ok(homeDTO);
    }

    @GetMapping("/onlineStatistics")
    @Operation(summary = "在线设备数统计", description = "折线统计")
    public R<List<HomeLineVO>> onlineStatistics(@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        validateDate(startDate, endDate);

        String tenantId = LoginHelper.getTenantId();
        List<HomeLineVO> homeDTO = homeService.onlineStatistics(tenantId, startDate, endDate);
        return R.ok(homeDTO);
    }

    /**
     * 校验日期参数
     */
    private void validateDate(LocalDate startDate, LocalDate endDate) {
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("开始日期和结束日期不能为空");
        }
        if (startDate.isAfter(endDate)) {
            throw new IllegalArgumentException("开始日期不能晚于结束日期");
        }
    }

}
